const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const cors = require('cors');
const path = require('path');

const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
});

// 中间件
app.use(cors());
app.use(express.json());

// 提供静态文件
app.use(express.static(path.join(__dirname, '../public')));

// 存储连接的客户端
const connectedClients = new Map();
const rooms = new Map();

// Socket.IO 连接处理
io.on('connection', (socket) => {
  console.log(`客户端连接: ${socket.id}`);

  // 加入房间
  socket.on('join-room', (roomId) => {
    socket.join(roomId);
    connectedClients.set(socket.id, { roomId, socket });
    
    if (!rooms.has(roomId)) {
      rooms.set(roomId, []);
    }
    rooms.get(roomId).push(socket.id);
    
    console.log(`客户端 ${socket.id} 加入房间 ${roomId}`);
    
    // 通知房间内其他用户有新用户加入
    socket.to(roomId).emit('user-joined', socket.id);
    
    // 发送房间内现有用户列表
    const roomUsers = rooms.get(roomId).filter(id => id !== socket.id);
    socket.emit('room-users', roomUsers);
  });

  // WebRTC 信令处理
  socket.on('offer', (data) => {
    console.log(`转发 offer 从 ${socket.id} 到 ${data.target}`);
    socket.to(data.target).emit('offer', {
      offer: data.offer,
      from: socket.id
    });
  });

  socket.on('answer', (data) => {
    console.log(`转发 answer 从 ${socket.id} 到 ${data.target}`);
    socket.to(data.target).emit('answer', {
      answer: data.answer,
      from: socket.id
    });
  });

  socket.on('ice-candidate', (data) => {
    console.log(`转发 ICE candidate 从 ${socket.id} 到 ${data.target}`);
    socket.to(data.target).emit('ice-candidate', {
      candidate: data.candidate,
      from: socket.id
    });
  });

  // 屏幕共享控制
  socket.on('start-screen-share', (roomId) => {
    console.log(`用户 ${socket.id} 开始屏幕共享在房间 ${roomId}`);
    socket.to(roomId).emit('screen-share-started', socket.id);
  });

  socket.on('stop-screen-share', (roomId) => {
    console.log(`用户 ${socket.id} 停止屏幕共享在房间 ${roomId}`);
    socket.to(roomId).emit('screen-share-stopped', socket.id);
  });

  // 远程控制事件
  socket.on('remote-control', (data) => {
    console.log(`转发远程控制事件从 ${socket.id} 到 ${data.target}`);
    socket.to(data.target).emit('remote-control', {
      event: data.event,
      from: socket.id
    });
  });

  // 断开连接处理
  socket.on('disconnect', () => {
    console.log(`客户端断开连接: ${socket.id}`);
    
    const clientInfo = connectedClients.get(socket.id);
    if (clientInfo) {
      const { roomId } = clientInfo;
      const roomUsers = rooms.get(roomId);
      if (roomUsers) {
        const index = roomUsers.indexOf(socket.id);
        if (index > -1) {
          roomUsers.splice(index, 1);
        }
        if (roomUsers.length === 0) {
          rooms.delete(roomId);
        }
      }
      connectedClients.delete(socket.id);
      
      // 通知房间内其他用户
      socket.to(roomId).emit('user-left', socket.id);
    }
  });
});

// API 路由
app.get('/api/rooms', (req, res) => {
  const roomList = Array.from(rooms.keys()).map(roomId => ({
    id: roomId,
    userCount: rooms.get(roomId).length
  }));
  res.json(roomList);
});

app.get('/api/room/:roomId', (req, res) => {
  const { roomId } = req.params;
  const roomUsers = rooms.get(roomId) || [];
  res.json({
    roomId,
    userCount: roomUsers.length,
    users: roomUsers
  });
});

// 前端路由处理
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '../public/index.html'));
});

const PORT = process.env.PORT || 3001;

server.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
  console.log(`访问 http://localhost:${PORT} 查看应用`);
}); 